
import { ElMessage } from 'element-plus'

interface IForm{
  submitFormData():Promise<any>;
}

class FormModal{
  id: number|undefined = undefined;//主键
  refId:number|undefined = undefined;//外键ID
  refName:string|undefined = undefined;//外键对象的名称
  params:any;
  visible:boolean = false;
  confirmLoading:boolean = false;//是否正在提交数据

  showModal(id:number|undefined=undefined, refId:number|undefined=undefined, refName:string|undefined=undefined, params:any={}){
    this.id = id;
    this.refId = refId;
    this.refName = refName;
    this.params = params;
    this.confirmLoading = false;
    this.visible = true;//打开表单弹窗
  }

  /**
   * 
   * @param form vue的form表单对象，比如 this.$refs.userForm;
   * @param okTip 提交保存成功后显示的提示信息，默认值为“数据保存成功”，不需要提示信息时可以设置 okTip='none'
   * @param showError 当出现措施时，是否弹出提示框，默认值：true
   */
  async submit(form :IForm, okTip:string='', showError:boolean = true){
    this.confirmLoading = true;//[确定]按钮变成加载状态
    try{
      debugger;
      let response = await form.submitFormData();
      this.visible = false;//关闭表单弹窗
      this.confirmLoading = false;//[确定]按钮变成正常状态
      if(okTip != 'none'){
        ElMessage.success(okTip || '数据保存成功');
      }
      return Promise.resolve(response);
    }catch(err:any){
      this.visible = true;//继续显示表单弹窗
      this.confirmLoading = false;//[确定]按钮变成正常状态
      if(err != 'validateError'){
        console.error(JSON.stringify(err));
        if(showError){
          ElMessage.error(err.errorMessage || err.message || JSON.stringify(err));
        }
      }else{//表单验证出错,不需要处理
        console.error("表单验证出错...");
      }
      return Promise.reject(err);
    }
  }
}

let formColGutter = 20;

export {FormModal,IForm, formColGutter}